<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg;
use \xg\facade\App;
use \xg\facade\Request;

class ErrorHandler {
	public static function showException(array $data){
		if(!$data['message']){
			$data['message']='unknown error';
		}
		if($data['debug']){
			$included = get_included_files();
			$sitePath = dirname(XG_PHP);
			foreach($included as $key=>$file) {
				$included[$key] = str_replace($sitePath,'',$file);
			}
			$data['file'] = str_replace($sitePath,'',$data['file']);
			$data['included'] = $included;
			$data['vars'] = [
				'GET'=>$_GET,
				'POST'=>$_POST,
				'COOKIE'=>$_COOKIE,
				'SESSION'=>$_SESSION,
				'SERVER'=>$_SERVER,
				'ENV'=>$_ENV,
				'FILES'=>$_FILES
			];
		}
		if(Request::isAjax()){
			$data['code']=-1;
			$response=Response::drive('json')->content($data)->code(200)->pretty();
		}else{
			$response=Response::drive('view')->fetch('exception',$data)->code($data['statusCode']?$data['statusCode']:500);
		}
		$response->send();
	}
	// 异常处理
	public static function appException($e){
		//判断是否是异常子类
		$isException=$e instanceof \Exception;
		$isError=(defined('XG_PHP_7') and $e instanceof \Error);
		if(!$isException and !$isError){
			return;
		}
		if(method_exists($e, 'getResponse')){
			$response = $e->getResponse();
			if($response){
				$response->send();
				return;
			}
		}
		
		// 处理状态码
		$statusCode = 500;
		if(method_exists($e, 'getStatusCode')){
			$statusCode = $e->getStatusCode();
		}
		
		$lang = App::get('lang');
		
		if($debug=App::debug()){
			$message = $e->getMessage();
			$code = $e->getCode();
			$trace = $e->getTrace();
			$file = $e->getFile();
			$line = $e->getLine();
			if(method_exists($e, 'getData')){
				$data = $e->getData();
			}
			$message=$lang->get($message,$data);
			self::showException([
				'debug'=>$debug,
				'statusCode'=>$statusCode,
				'message'=>$message,
				'data'=>$data,
				'code'=>$code,
				'file'=>$file,
				'line'=>$line,
				'trace'=>$trace
			]);
		}else{
			self::showException([
				'statusCode'=>$statusCode,
				'message'=>$lang->get('error occurred please try again later')
			]);
		}
	}
}
